from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

# widget code
class isoTransform(OWRpy): 
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # Unique R variables
        self.setRvariableNames(["isometric", "defaultILRbase"])
        
        # Python variables
        self.data = {}
        self.RFunctionParam_x = ''
        self.SBP = ''
        
        # Inputs
        self.inputs.addInput("x", "Compositional data", signals.base.RMatrix, self.processx)
        self.inputs.addInput("SBP", "Sequential binary partition", signals.base.RMatrix, self.processSBP)
        
        # Output
        self.outputs.addOutput("isoTransform Output","isoTransform Output", signals.base.RMatrix)
        
        # GUI
        if self.SBP == '':
            self.status.setText('SBP is missing. Default will be used.')
        self.dataClass = redRGUI.base.lineEdit(self.controlArea, label = "Data class:", text = '')
        self.dataClass.setDisabled(True)
        self.isoOpLabel = redRGUI.base.lineEdit(self.controlArea, label = "Isometric operation:", text = '')
        self.isoOpLabel.setDisabled(True)
        self.sbpOrigin = redRGUI.base.lineEdit(self.controlArea, label = "SBP origin:", text = 'Default')
        self.sbpOrigin.setDisabled(True)
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignRight, 
        callback = self.commitFunction, processOnInput=True)
        
    def processx(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_x=data.getData()
            #self.data = data
            self.dataClass.setText(self.R('class('+self.RFunctionParam_x+')'))
            if self.dataClass.text() =='rplus' :
                self.isoOpLabel.setText('Isometric identity transform')
            elif self.dataClass.text() =='aplus' :
                self.isoOpLabel.setText('Isometric log transform')
            elif self.dataClass.text() =='rcomp' :
                self.isoOpLabel.setText('Isometric planar transform')
            elif self.dataClass.text() =='acomp' :
                self.isoOpLabel.setText('Isometric log-ratio transform')
            else :
                self.status.setText('The class of the input is not compositional. Please parse data though widget "Close the simplex".')
                return
            self.commitFunction()
        else:
            self.RFunctionParam_x=''

    def processSBP(self, data):
        if not self.require_librarys(["compositions"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.status.setText('Custom SBP will be used.')
            self.SBP=data.getData()
            #self.data = data
            self.sbpOrigin.setText('Custom')
            self.commitFunction()
        else:
            self.SBP=''
            self.sbpOrigin.setText('Default')
            self.commitFunction()

    def commitFunction(self):
        if str(self.RFunctionParam_x) == '': 
            self.status.setText('Compositionnal data is missing.')
            return
        
        # SBP: if no SBP, create default, else import from Input
        if self.SBP == '':
            self.R('defaultSBP<-as.data.frame(gsi.ilrBase2signary(t(ilrBase('+self.RFunctionParam_x+'))))', wantType = 'NoConversion')
            self.R(self.Rvariables['defaultILRbase']+'<-gsi.buildilrBase(t(as.data.frame(defaultSBP)))')
        else:
            self.R(self.Rvariables['defaultILRbase']+'<-gsi.buildilrBase(t(as.data.frame('+str(self.SBP)+')))')
            ncolX=self.R('ncol('+str(self.RFunctionParam_x)+')')
            ncolSBP=self.R('ncol('+str(self.SBP)+')')
            if ncolX != ncolSBP:
                self.status.setText('SBP has wrong dimensions.')
                return

        injection = []
        string = 'V='+self.Rvariables['defaultILRbase']+''
        injection.append(string)
        inj = ','.join(injection)
        
        # Compute isometric transformation
        self.R(self.Rvariables['isometric']+'<-idt(x='+str(self.RFunctionParam_x)+','+inj+')')
        
        # Send data
        newData = signals.base.RMatrix(self, data = self.Rvariables['isometric'], checkVal = False)
        self.rSend("isoTransform Output", newData)